﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Infrastructure.ViewModels;
using UI.Controls.Dictionaries;

namespace UI.Dialogs.Dictionaries.Builders
{
    public class ConditionBuilder : DictionaryBuilder
    {
        readonly ConditionGrid _grid;
        readonly ConditionDetailed _addForm;
        readonly ConditionDetailed _editForm;

        public ConditionBuilder(DictionaryFormBase form) : base(form)
        {
            form.Title = "Condition";

            _addForm = new ConditionDetailed();
            _editForm = new ConditionDetailed();

            _grid = new ConditionGrid();

            _grid.SelectionChanged += delegate(object sender, SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    _editForm.Item = args.AddedItems[0] as ConditionViewModel;
                }
            };
            _grid.SelectionChanged += SelectionChanged;

            Form.AddClicked += delegate { Save(); };
            Form.SaveClicked += delegate { Update(); };
        }

        #region Overrides of DictionaryBuilder

        /// <summary>
        /// Builds the dictionary form and functionality.
        /// </summary>
        public override void Build()
        {
            Form.GridControl = _grid;
            Form.AddControl = _addForm;
            Form.EditControl = _editForm;
        }

        /// <summary>
        /// Updates the selected item.
        /// </summary>
        public override void Update()
        {
            _editForm.Save.Execute(null);
        }

        /// <summary>
        /// Saves the new item.
        /// </summary>
        public override void Save()
        {
            _addForm.Save.Execute(null);
        }

        /// <summary>
        /// Sets the selected item.
        /// </summary>
        /// <param name="item">The item.</param>
        public override void SetSelected(object item)
        {
            _grid.Selected = item;
        }

        /// <summary>
        /// Updates the grid.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <param name="item">The item.</param>
        public override void UpdateGrid(UpdateOperation operation, object item)
        {
            _grid.UpdateGrid(operation, item);
        }

        #endregion

        protected override void SelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            base.SelectionChanged(sender, args);

            if (args.AddedItems.Count > 0)
            {
                _editForm.Item = args.AddedItems[0] as ConditionViewModel;
            }
        }
    }
}
